/**
 * 用户界面交互模块
 * 处理DOM操作和事件监听
 */

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 绑定按钮事件
    document.getElementById('easy-btn').addEventListener('click', function() {
        initGame(3);
        showGameSection();
    });
    
    document.getElementById('medium-btn').addEventListener('click', function() {
        initGame(4);
        showGameSection();
    });
    
    document.getElementById('hard-btn').addEventListener('click', function() {
        initGame(5);
        showGameSection();
    });
    
    document.getElementById('beginner-btn').addEventListener('click', function() {
        initGame(2);
        showGameSection();
    });
    
    document.getElementById('leaderboard-btn').addEventListener('click', function() {
        showLeaderboard();
    });
    
    document.getElementById('back-btn').addEventListener('click', function() {
        returnToMenu();
    });
    
    document.getElementById('play-again-btn').addEventListener('click', function() {
        initGame(gameState.size);
        hideGameComplete();
    });
    
    document.getElementById('menu-btn').addEventListener('click', function() {
        returnToMenu();
    });
    
    document.getElementById('back-from-leaderboard').addEventListener('click', function() {
        returnToMenu();
    });
    
    // 新增：图片上传事件
    var uploadInput = document.getElementById('upload-img');
    if (uploadInput) {
        uploadInput.addEventListener('change', function(e) {
            var file = e.target.files[0];
            if (!file) return;
            var reader = new FileReader();
            reader.onload = function(evt) {
                var imgUrl = evt.target.result;
                puzzleImages.push(imgUrl);
                currentPuzzleImg = imgUrl;
                var originalImg = document.getElementById('original-image');
                if(originalImg) originalImg.src = imgUrl;
                initGame(gameState.size || 3);
                showGameSection();
            };
            reader.readAsDataURL(file);
        });
    }
    
    document.getElementById('reset-img-btn').addEventListener('click', function() {
        currentPuzzleImg = puzzleImages[0];
        var originalImg = document.getElementById('original-image');
        if(originalImg) originalImg.src = currentPuzzleImg;
        initGame(gameState.size || 3);
        showGameSection();
    });
});

// 可用拼图图片列表
var puzzleImages = [
    'img/cartoon1.jpg',
    'img/cartoon2.jpg',
    'img/cartoon3.jpg',
    'img/cartoon4.jpg',
    'img/cartoon5.jpg'
];
// 当前拼图图片
var currentPuzzleImg = puzzleImages[0];

// 修改 initGame 逻辑
var _oldInitGame = initGame;
initGame = function(size) {
    // 只有不是用户上传图片时才随机
    if (!currentPuzzleImg || !puzzleImages.includes(currentPuzzleImg) || currentPuzzleImg.startsWith('img/')) {
        currentPuzzleImg = puzzleImages[Math.floor(Math.random() * puzzleImages.length)];
    }
    // 同步原图
    var originalImg = document.getElementById('original-image');
    if(originalImg) originalImg.src = currentPuzzleImg;
    _oldInitGame(size);
}

// 渲染拼图板
function renderBoard() {
    var boardElement = document.getElementById('puzzle-board');
    boardElement.innerHTML = '';
    boardElement.style.width = (gameState.size * 100) + 'px';
    boardElement.style.height = (gameState.size * 100) + 'px';
    
    var imgUrl = currentPuzzleImg;
    var tileSize = 100;
    var bgSize = (gameState.size * tileSize) + 'px';

    for (var y = 0; y < gameState.size; y++) {
        for (var x = 0; x < gameState.size; x++) {
            var value = gameState.board[y][x];
            if (value === 0) {
                continue; // 空白块不渲染
            }

            var tile = document.createElement('div');
            tile.className = 'puzzle-tile';
            // 计算原始图片中的行列
            var originIndex = value - 1;
            var originY = Math.floor(originIndex / gameState.size);
            var originX = originIndex % gameState.size;
            tile.style.backgroundImage = 'url(' + imgUrl + ')';
            tile.style.backgroundSize = bgSize + ' ' + bgSize;
            tile.style.backgroundPosition = '-' + (originX * tileSize) + 'px -' + (originY * tileSize) + 'px';
            tile.style.left = (x * tileSize) + 'px';
            tile.style.top = (y * tileSize) + 'px';
            // 不再显示数字
            tile.textContent = '';

            // 添加点击事件
            tile.addEventListener('click', (function(posX, posY) {
                return function() {
                    moveTile(posX, posY);
                };
            })(x, y));

            boardElement.appendChild(tile);
        }
    }
}

// 更新移动步数显示
function updateMoveCount() {
    document.getElementById('move-count').textContent = gameState.moves;
}

// 更新时间显示
function updateTimeDisplay() {
    document.getElementById('time-count').textContent = gameState.time;
}

// 显示游戏完成界面
function showGameComplete() {
    document.getElementById('final-time').textContent = gameState.time;
    document.getElementById('final-moves').textContent = gameState.moves;
    document.getElementById('game-complete').classList.remove('hidden');
}

// 隐藏游戏完成界面
function hideGameComplete() {
    document.getElementById('game-complete').classList.add('hidden');
}

// 显示游戏区域
function showGameSection() {
    document.getElementById('main-menu').classList.add('hidden');
    document.getElementById('leaderboard-section').classList.add('hidden');
    document.getElementById('game-section').classList.remove('hidden');
}

// 排行榜难度切换
var leaderboardDifficulty = 3; // 默认3x3
function renderLeaderboardDifficultyButtons() {
    var container = document.getElementById('leaderboard-difficulty-buttons');
    if (!container) {
        container = document.createElement('div');
        container.id = 'leaderboard-difficulty-buttons';
        container.style.marginBottom = '18px';
        document.getElementById('leaderboard-section').insertBefore(container, document.getElementById('leaderboard-chart'));
    }
    var html = '';
    [2,3,4,5].forEach(function(size) {
        html += '<button class="btn' + (leaderboardDifficulty===size?'':' secondary') + '" data-size="'+size+'">' + size + '×' + size + '</button>';
    });
    container.innerHTML = html;
    Array.from(container.querySelectorAll('button')).forEach(function(btn){
        btn.onclick = function(){
            leaderboardDifficulty = parseInt(btn.getAttribute('data-size'));
            renderLeaderboard();
            renderLeaderboardDifficultyButtons();
        };
    });
}

// 修改排行榜渲染，按当前难度显示
function renderLeaderboard() {
    var chart = echarts.init(document.getElementById('leaderboard-chart'));
    var scores = getScores(leaderboardDifficulty) || [];
    var option = {
        title: {
            text: leaderboardDifficulty + '×' + leaderboardDifficulty + ' 最佳成绩排行榜',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                var score = scores[params[0].dataIndex];
                return [
                    '难度: ' + score.size + '×' + score.size,
                    '用时: ' + score.time + '秒',
                    '步数: ' + score.moves,
                    '日期: ' + score.date
                ].join('<br/>');
            }
        },
        xAxis: {
            type: 'category',
            data: scores.map(function(_, i) { return '第' + (i+1) + '名'; }),
            axisLabel: {
                interval: 0,
                rotate: 0
            }
        },
        yAxis: {
            type: 'value',
            name: '用时(秒)'
        },
        series: [{
            name: '用时',
            type: 'bar',
            data: scores.map(function(score) { return score.time; }),
            itemStyle: {
                color: function(params) {
                    var colorList = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6'];
                    return colorList[params.dataIndex % colorList.length];
                }
            },
            label: {
                show: true,
                position: 'top',
                formatter: function(params) {
                    return scores[params.dataIndex].size + '×' + scores[params.dataIndex].size;
                }
            }
        }]
    };
    chart.setOption(option);
    // 渲染表格
    var table = document.getElementById('leaderboard-table');
    if (!scores.length) {
        table.innerHTML = '<tr><td>暂无记录</td></tr>';
        return;
    }
    var html = '<tr><th>排名</th><th>难度</th><th>用时(秒)</th><th>步数</th><th>日期</th></tr>';
    for (var i = 0; i < scores.length; i++) {
        html += '<tr>' +
            '<td>' + (i+1) + '</td>' +
            '<td>' + scores[i].size + '×' + scores[i].size + '</td>' +
            '<td>' + scores[i].time + '</td>' +
            '<td>' + scores[i].moves + '</td>' +
            '<td>' + scores[i].date + '</td>' +
            '</tr>';
    }
    table.innerHTML = html;
}

// 只保留一个 showLeaderboard
function showLeaderboard() {
    document.getElementById('main-menu').classList.add('hidden');
    document.getElementById('game-section').classList.add('hidden');
    document.getElementById('leaderboard-section').classList.remove('hidden');
    renderLeaderboardDifficultyButtons();
    renderLeaderboard();
}

// 返回主菜单
function returnToMenu() {
    // 停止游戏计时器
    if (gameState.timer) {
        clearInterval(gameState.timer);
    }
    
    document.getElementById('game-section').classList.add('hidden');
    document.getElementById('leaderboard-section').classList.add('hidden');
    document.getElementById('game-complete').classList.add('hidden');
    document.getElementById('main-menu').classList.remove('hidden');
}